<?php
/*
 *
 * @author Faker
 * @date 2020-12-16 17:37
 */

namespace app\index\controller;

use app\common\controller\UserCm;
use think\Controller;
use think\Hook;
use think\Session;

class BaseController extends controller
{
    protected $path='index/index';

    protected $username = '';
    protected $sid = '';
    protected $db;


    /**
     * 前置验证函数,验证用户是否在线
     */
    protected function _initialize()
    {
//        header("Access-Control-Allow-Origin: *"); // 允许任意域名发起的跨域请求
        $username = $this->request->param('user');
        $sid = $this->request->param('sid');
        $this->username = $username;
        $this->sid = $sid;
//        $this->check();
        $this->login();
    }

    /**
     * 校验用户是否在线信息
     * @param string $username 用户名
     * @param string $sid 在线标志
     * @return bool
     */
    protected function CheckSid($username, $sid)
    {
        $obj_manager = new UserCm();
        $sid_db = $obj_manager->GetField($username, 'sid');
        if ($sid != $sid_db || !isset($sid)) {
//            return $this->error('请登录！','/login');
//            $this->ApiReturnMsg(2, '您已离线，请重新登陆 ');
            return true;
        }
        return false;
    }

    /**session接口
     * @author LeeBW
     * @date 2020-12-16 15:50
     */
    public function login(){
        if(Session::has('name')){
            $name=Session::get('name');
            $level=Session::get('level');
        }else{
            $name=null;
            $level = null;
        }
        $this->assign(['name'=>$name,'level'=>$level]);
    }

    /**
     * 检查用户是否登录
     * @author LeeBW
     * @date 2020-12-16 15:30
     */
    public function check(){
        if(!Session::has('name')){
            Hook::listen('CheckAuth',$params);
        }
    }
    /**
     * IP地址
     */
    public static function get_ip()
    {
        if (@$_SERVER["HTTP_X_FORWARDED_FOR"])
            $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
        else if (@$_SERVER["HTTP_CLIENT_IP"])
            $ip = $_SERVER["HTTP_CLIENT_IP"];
        else if (@$_SERVER["REMOTE_ADDR"])
            $ip = $_SERVER["REMOTE_ADDR"];
        else if (@getenv("HTTP_X_FORWARDED_FOR"))
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        else if (@getenv("HTTP_CLIENT_IP"))
            $ip = getenv("HTTP_CLIENT_IP");
        else if (@getenv("REMOTE_ADDR"))
            $ip = getenv("REMOTE_ADDR");
        else
            $ip = "Unknown";
        return $ip;
    }

    /**
     * 无数据请求结果返回函数
     * @param string $status 请求返回状态  0:成功 1:失败
     * @param string $msg 请求结果消息
     * @return mixed    输出结果
     */
    protected function ApiReturnMsg($status, $msg)
    {
        header('Content-type: application/json');
        $arrJson['status'] = $status;
        $arrJson['msg'] = $msg;
        echo json_encode($arrJson);
        exit();
    }


}